package org.arclib;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;

import org.arclib.math.Size;
import org.lwjgl.opengl.GL11;

/**
 * A texture to be bound within JOGL. This object is responsible for keeping
 * track of a given OpenGL texture and for calculating the texturing mapping
 * coordinates of the full image.
 * 
 * Since textures need to be powers of 2 the actual texture may be considerably
 * bigged that the source image and hence the texture mapping coordinates need
 * to be adjusted to matchup drawing the sprite against the texture.
 * 
 * @author Kevin Glass
 * @author Brian Matzon
 */
public class Texture
{
	private int ID;
	private Size displaySize;
	private Size originalSize;

	Texture(int argID)
	{
		ID = argID;
	}

	public Size getSize()
	{
		return displaySize;
	}

	public Size getImageSize()
	{
		return originalSize;
	}

	/**
	 * This is the actual image size Should only be set by the texture loader
	 * 
	 * @param argSize
	 */
	protected void setImageSize(Size argSize)
	{
		originalSize = argSize;
	}

	/**
	 * This is the image size after power of two size Should only be set by
	 * texture loader
	 * 
	 * @param argSize
	 */
	protected void setSize(Size argSize)
	{
		displaySize = argSize;
	}

	/**
	 * Destroy the texture reference
	 */
	public void release()
	{
		IntBuffer texBuf = createIntBuffer(1);
		texBuf.put(ID);
		texBuf.flip();

		GL11.glDeleteTextures(texBuf);
	}

	/**
	 * Get the OpenGL texture ID for this texture
	 * 
	 * @return The OpenGL texture ID
	 */

	/**
	 * Creates an integer buffer to hold specified ints - strictly a utility
	 * method
	 * 
	 * @param size
	 *            how many int to contain
	 * @return created IntBuffer
	 */
	protected IntBuffer createIntBuffer(int size)
	{
		ByteBuffer temp = ByteBuffer.allocateDirect(4 * size);
		temp.order(ByteOrder.nativeOrder());

		return temp.asIntBuffer();
	}

	void bind()
	{
		GL11.glEnable(GL11.GL_TEXTURE_2D);

		// bind texture ID to this texture
		GL11.glBindTexture(GL11.GL_TEXTURE_2D, getID());
	}

	public int getID()
	{
		// TODO Auto-generated method stub
		return ID;
	}
}
